<?php
namespace app\common\model;
use app\common\cache\CacheData;

class BonusConfig extends Base
{
	
	public function cacheData(){
		$data = $this->select();
		if($data){
			foreach($data as &$value):
				$value = $value->toArray();
			endforeach;
		}
		return $data;
	}
    
    // /**
    //  * 按奖金名称获取奖金配置缓存
    //  * @return [type] [description]
    //  */
    // public static function bonusConfigByDir($bonus_name=null){
    //     $CACHE = CacheData::getInstance('BonusConfig');
    //     $cacheData = $CACHE -> readCache();
    //     $data = [];
    //     foreach($cacheData as $cache):
    //         $data[$cache['bonus_name']][] = $cache;
    //     endforeach;
    //     if(!is_null($bonus_name)){
    //         if(isset($data[$bonus_name])):
    //             return $data[$bonus_name];
    //         else:
    //             return false;
    //         endif;
    //     }else{
    //         return $data;
    //     }
    // }

    /**
     * 获取奖金的某类配置项
     * @param  [type] $bonus_name [description]
     * @param  [type] $config_name [description]
     * @return [type]              [description]
     */
    public static function bonusConfig($bonus_name,$config_name){
        $CACHE = CacheData::getInstance('BonusConfig');
        $CACHE -> updateCache();
        $cacheData = $CACHE -> readCache();

        $return = sameKeyValueArray($cacheData,['bonus_name'=>$bonus_name,'config_name'=>$config_name]);
        if(!empty($return)){
            if(sizeof($return)>1)
                return $return;
            else
                return $return[0];
        }
        
    }

    public function saveOneData($data){
        if($this->isExist($data['bonus_name'],$data['config_name'])){
            $this -> where(['bonus_name'=>$data['bonus_name'],'config_name'=>$data['config_name']]) -> update(['config_value'=>$data['config_value']]);
        }else{
            $this -> allowField(true) -> save($data);
        }
    }

    private function isExist($bonus_name,$config_name){
        if($this->where(['bonus_name'=>$bonus_name,'config_name'=>$config_name])->find()){
            return true;
        }else{
            return false;
        }
    }

}
